import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/binding_terminal_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/edit_fix_camera_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/binding_terminal_auto_switch_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/camera_distance_widget.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/camera_face_size_widget.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/common_terminal_settings_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/set_terminal_state_type.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_auto_onoff_page.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../set_auto_onoff_page_by_each_day.dart';
import 'bean/binding_terminal_edit_upload_bean.dart';
import 'bean/binding_terminal_response_bean.dart';
import 'bean/binding_terminal_type.dart';
import 'bind_terminal_more_settings_page.dart';

/// 更多设置页面
class EditMoreSettingsPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "EditMoreSettingsPage";
  final String hsn;
  final String router;
  final TerminalInfoBean terminalInfoBean;
  final int terminalCount;
  const EditMoreSettingsPage({Key key, this.hsn, this.terminalInfoBean,
    this.terminalCount, this.router})
      : super(key: key);

  @override
  _EditMoreSettingsPageState createState() => _EditMoreSettingsPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(
      BuildContext context, String hsn, TerminalInfoBean terminalInfoBean, {int terminalCount, String router}) {
    return RouterUtils.routeForFutureResult(
      context,
      EditMoreSettingsPage(
        hsn: hsn,
        terminalInfoBean:terminalInfoBean,
        terminalCount: terminalCount,
        router: router,
      ),
      routeName: EditMoreSettingsPage.ROUTER,
    );
  }
}

class _EditMoreSettingsPageState extends BaseState<EditMoreSettingsPage> {

  BindingTerminalViewModel _viewModel;
  ComAutoSwitchBean _autoBean;

  @override
  void initState() {
    super.initState();
    _viewModel = BindingTerminalViewModel(this);
    _autoBean = widget?.terminalInfoBean?.comAutoSwitch;
    widget?.terminalInfoBean?.startDateTime = widget?.terminalInfoBean?.getStartOrEndTime(
        widget?.terminalInfoBean?.autoOnoffTime, 0);
    widget?.terminalInfoBean?.endDateTime = widget?.terminalInfoBean?.getStartOrEndTime(
        widget?.terminalInfoBean?.autoOnoffTime, 1);
    Future((){
      VgToolUtils.removeAllFocus(context);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _toInfoWidget(),
    );
  }

  Widget _toInfoWidget(){
    String autoOnOffTime = getWeekAutoOnOffTimeStr();
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Container(
          padding: EdgeInsets.only(left: 15, right: 16),
          decoration: BoxDecoration(
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Visibility(
                visible: StringUtils.isNotEmpty(widget?.terminalInfoBean?.appedition)?widget?.terminalInfoBean?.isShowFaceRecognition():
                UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition(),
                child: Column(
                  children: [
                    SizedBox(height: 13,),
                    ///摄像头校正
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: ()async{
                        dynamic result = await EditFixCameraPage.navigatorPush(context, widget?.terminalInfoBean);
                        if(result == null){
                          _viewModel.exitBindTerminal(widget?.hsn);
                        }
                      },
                      child: Container(
                        height: 50,
                        child: Row(
                          children: <Widget>[
                            Text(
                              "摄像头校正",
                              style: TextStyle(
                                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                                  fontSize: 14
                              ),
                            ),
                            Spacer(),
                            Row(
                              children: <Widget>[
                                Text(
                                  (widget?.terminalInfoBean?.correctCamera == null
                                      ||StringUtils.isEmpty(widget?.terminalInfoBean?.cameratype)) ?"":"已校正",
                                  style: TextStyle(
                                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                                      fontSize: 14
                                  ),
                                ),
                                SizedBox(width: 10,),
                                Image.asset(
                                  "images/index_arrow_ico.png",
                                  width: 6,
                                ),
                              ],
                            ),

                          ],
                        ),
                      ),
                    ),
                    _toSplitLineWidget(),
                    ///人脸识别框大小
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: ()async{
                        // BindTerminalMoreSettingsPage.navigatorPush(context, widget?.hsn, new BindingTermialEditUploadBean());
                        double result= await CameraFaceSizeWidget.navigatorPush(context, widget?.terminalInfoBean?.getFaceSizeDouble());
                        if(result!=null){
                          widget?.terminalInfoBean?.frame = result.toInt();
                          setState(() {});
                          _viewModel.setFaceSize(widget?.terminalInfoBean?.mid, widget?.terminalInfoBean?.id,
                              widget?.terminalInfoBean?.hsn, "01", widget?.terminalInfoBean?.frame);
                          print("人脸识别框大小$result");
                        }
                      },
                      child: Container(
                        height: 50,
                        child: Row(
                          children: <Widget>[
                            Text(
                              "人脸识别框大小",
                              style: TextStyle(
                                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                                  fontSize: 14
                              ),
                            ),
                            Spacer(),
                            Row(
                              children: <Widget>[
                                Text(
                                  widget?.terminalInfoBean?.frame == null?"适中":widget?.terminalInfoBean?.getFaceSizeStr(),
                                  style: TextStyle(
                                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                                      fontSize: 14
                                  ),
                                ),
                                SizedBox(width: 10,),
                                Image.asset(
                                  "images/index_arrow_ico.png",
                                  width: 6,
                                )
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    _toSplitLineWidget(),
                    ///摄像头启动距离
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: ()async{
                        double result= await CameraDistanceWidget.navigatorPush(context, widget?.terminalInfoBean?.getCameraStartDistanceValue());
                        if(result!=null){
                          widget?.terminalInfoBean?.startCameraDistance = _getDistance(result);
                          setState(() {});
                          _viewModel.setCameraStartDistance(widget?.terminalInfoBean?.mid, widget?.terminalInfoBean?.id,
                              widget?.terminalInfoBean?.hsn, "01", widget?.terminalInfoBean?.startCameraDistance);
                          print("摄像头启动距离$result");
                        }
                      },
                      child: Container(
                        height: 50,
                        child: Row(
                          children: <Widget>[
                            Text(
                              "摄像头启动距离",
                              style: TextStyle(
                                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                                  fontSize: 14
                              ),
                            ),
                            Spacer(),
                            Row(
                              children: <Widget>[
                                Text(
                                  widget?.terminalInfoBean?.startCameraDistance == null?"-":widget?.terminalInfoBean?.getCameraStartDistanceStr(),
                                  style: TextStyle(
                                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                                      fontSize: 14
                                  ),
                                ),
                                SizedBox(width: 10,),
                                Image.asset(
                                  "images/index_arrow_ico.png",
                                  width: 6,
                                )
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    _toSplitLineWidget(),
                    ///刷脸记录间隔
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: (){
                        return SelectUtil.showListSelectDialog(
                            context: context,
                            title: "刷脸记录间隔",
                            positionStr: widget?.terminalInfoBean?.getPunchInIntervalStr(),
                            textList: ConstantRepository.of().getPunchInInterval(),
                            onSelect: (dynamic value) {
                              if(value.toString().contains("小时")){
                                widget?.terminalInfoBean?.timeInterval = (double.parse(value.toString().replaceAll("小时", ""))*60).floor();
                              }else{
                                widget?.terminalInfoBean?.timeInterval = int.parse(value.toString().replaceAll("分钟", ""));
                              }
                              setState(() {});
                              _viewModel.setPunchInInterval(widget?.terminalInfoBean?.mid, widget?.terminalInfoBean?.id,
                                  widget?.terminalInfoBean?.hsn, "01", widget?.terminalInfoBean?.timeInterval);
                            }
                        );
                      },
                      child: Container(
                        height: 50,
                        child: Row(
                          children: <Widget>[
                            Text(
                              "刷脸记录间隔",
                              style: TextStyle(
                                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                                  fontSize: 14
                              ),
                            ),
                            Spacer(),
                            Row(
                              children: <Widget>[
                                Text(
                                  widget?.terminalInfoBean?.timeInterval == null?"-":widget?.terminalInfoBean?.getPunchInIntervalStr(),
                                  style: TextStyle(
                                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                                      fontSize: 14
                                  ),
                                ),
                                SizedBox(width: 10,),
                                Image.asset(
                                  "images/index_arrow_ico.png",
                                  width: 6,
                                )
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    Visibility(
                        visible: true,
                        child: _toSplitLineWidget()
                    ),
                  ],
                ),
              ),
              ///自动开关机
              Visibility(
                visible: true,
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () async {
                    if(StringUtils.isEmpty(autoOnOffTime) || ("00" == _autoBean?.autoOnoff)){
                      return;
                    }

                    SetAutoOnOffByEachDayPage.navigatorPush(context, _autoBean, (comAutoSwitchBean){
                      _viewModel.saveAutoOnOffByWeek(context, widget?.hsn, widget?.terminalInfoBean?.id, comAutoSwitchBean, needPop: false);
                      setState(() {
                        _autoBean = comAutoSwitchBean;
                      });
                      if(widget?.terminalInfoBean?.getTerminalState() == SetTerminalStateType.off){
                        CommonISeeDialog.navigatorPushDialog(context, title: "提示",
                            content:"当前显示屏已关机，定时设置将在开机后生效");
                      }
                    }, hsn: widget?.hsn, rcaid: widget?.terminalInfoBean?.id,
                        callback: (){
                          if(widget?.terminalInfoBean?.getTerminalState() == SetTerminalStateType.off){
                            CommonISeeDialog.navigatorPushDialog(context, title: "提示",
                                content:"当前显示屏已关机，定时设置将在开机后生效");
                          }
                        });

                    // if(StringUtils.isEmpty(widget?.terminalInfoBean?.autoOnoffTime) || ("00" == widget?.terminalInfoBean?.autoOnoff)){
                    //   return;
                    // }
                    // SetAutoOnOffPage.navigatorPushDialog(context,
                    //     widget?.terminalInfoBean?.startDateTime,
                    //   widget?.terminalInfoBean?.endDateTime,
                    //   widget?.terminalInfoBean?.autoOnoffWeek,
                    //     (String time, String week){
                    //       //auto_onoff 00未设置 01已设置
                    //       if(StringUtils.isEmpty(time)){
                    //         //自动开关机时间为空，代表未设置
                    //         _viewModel.setAutoOnOffTime(widget?.terminalInfoBean?.id,
                    //             widget?.hsn, "01", widget?.terminalInfoBean?.autoOnoffTime, "00", widget?.terminalInfoBean?.autoOnoffWeek, needPop: true);
                    //       }else{
                    //         _viewModel.setAutoOnOffTime(widget?.terminalInfoBean?.id,
                    //             widget?.hsn, "01", time, "01", week, needPop: true);
                    //       }
                    //       setState(() {});
                    //     }
                    // );
                    // _toSetAutoOnOffTime();
                  },
                  child: Container(
                    height: 50,
                    child: Row(
                      children: <Widget>[
                        Text(
                          "定时开关机",
                          style: TextStyle(
                              color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                              fontSize: 14
                          ),
                        ),
                        Spacer(),
                        Visibility(
                          // visible: StringUtils.isNotEmpty(widget?.terminalInfoBean?.autoOnoffTime) && ("01" == widget?.terminalInfoBean.autoOnoff),
                          visible: StringUtils.isNotEmpty(autoOnOffTime) && ("01" == _autoBean?.autoOnoff),
                          child: Row(
                            children: <Widget>[
                              Text(
                                autoOnOffTime,
                                style: TextStyle(
                                  // color: widget?.terminalInfoBean?.startDateTime == null ||
                                  //     widget?.terminalInfoBean?.endDateTime == null
                                  //     ? ThemeRepository.getInstance()
                                  //     .getTextEditHintColor_3A3F50()
                                  //     : ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                                    color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                                    fontSize: 14
                                ),
                              ),
                              SizedBox(width: 10,),
                              Image.asset(
                                "images/index_arrow_ico.png",
                                width: 6,
                              )
                            ],
                          ),
                        ),
                        GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: (){
                            //auto_onoff 00未设置 01已设置
                            if(StringUtils.isNotEmpty(autoOnOffTime)){
                              setState(() {
                                _autoBean?.autoOnoff = "01";
                              });
                              _viewModel.saveAutoOnOffByWeek(context, widget?.hsn,
                                  widget?.terminalInfoBean?.id,
                                  _autoBean,
                                  needPop: false,
                                  noToast: true,
                                  //打开之后进入设置页面
                                  callback: (){
                                    SetAutoOnOffByEachDayPage.navigatorPush(context,
                                        _autoBean,
                                        (comAutoSwitchBean){
                                          _viewModel.saveAutoOnOffByWeek(context, widget?.hsn, widget?.terminalInfoBean?.id,comAutoSwitchBean, needPop: true);
                                          setState(() {
                                            _autoBean = comAutoSwitchBean;
                                          });
                                        },
                                        hsn: widget?.hsn,
                                        rcaid: widget?.terminalInfoBean?.id,
                                        callback: (){
                                          // RouterUtils.pop(context);
                                          if(widget?.terminalInfoBean?.getTerminalState() == SetTerminalStateType.off){
                                          CommonISeeDialog.navigatorPushDialog(context, title: "提示",
                                              content:"当前显示屏已关机，定时设置将在开机后生效");
                                          }
                                        },
                                        showOffHint: widget?.terminalInfoBean?.getTerminalState() == SetTerminalStateType.off
                                    );
                                  }
                              );
                            }else{
                              SetAutoOnOffByEachDayPage.navigatorPush(context, _autoBean, (comAutoSwitchBean){
                                _viewModel.saveAutoOnOffByWeek(context, widget?.hsn, widget?.terminalInfoBean?.id,comAutoSwitchBean, needPop: true);
                                setState(() {
                                  _autoBean = comAutoSwitchBean;
                                });
                              }, hsn: widget?.hsn, rcaid: widget?.terminalInfoBean?.id);
                            }
                            // if(StringUtils.isNotEmpty(widget?.terminalInfoBean?.autoOnoffTime)){
                            //   _viewModel.setAutoOnOffTime(widget?.terminalInfoBean?.id,
                            //       widget?.hsn, "01", widget?.terminalInfoBean?.autoOnoffTime,
                            //       "01", widget?.terminalInfoBean?.autoOnoffWeek, needPop: true);
                            // }else{
                            //   SetAutoOnOffPage.navigatorPushDialog(context,
                            //       widget?.terminalInfoBean?.startDateTime,
                            //       widget?.terminalInfoBean?.endDateTime,
                            //       widget?.terminalInfoBean?.autoOnoffWeek,
                            //           (String time, String week){
                            //         //auto_onoff 00未设置 01已设置
                            //         if(StringUtils.isEmpty(time)){
                            //           //自动开关机时间为空，代表未设置
                            //           _viewModel.setAutoOnOffTime(widget?.terminalInfoBean?.id,
                            //               widget?.hsn, "01", widget?.terminalInfoBean?.autoOnoffTime, "00", widget?.terminalInfoBean?.autoOnoffWeek, needPop: true);
                            //         }else{
                            //           _viewModel.setAutoOnOffTime(widget?.terminalInfoBean?.id,
                            //               widget?.hsn, "01", time, "01", week, needPop: true);
                            //         }
                            //         setState(() {});
                            //       }
                            //   );
                            //   // _toSetAutoOnOffTime();
                            // }
                          },
                          child: Visibility(
                            // visible: StringUtils.isEmpty(widget?.terminalInfoBean?.autoOnoffTime) || ("00" == widget?.terminalInfoBean?.autoOnoff),
                            visible: StringUtils.isEmpty(autoOnOffTime) || ("00" == _autoBean?.autoOnoff),
                            child: Image.asset(
                              "images/icon_close.png",
                              width: 36,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        Spacer(),
        Visibility(
          visible: VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId()),
          child: GestureDetector(
            onTap: ()async{
              bool result =
              await CommonConfirmCancelDialog.navigatorPushDialog(context,
                  title: "提示",
                  content: "确定解绑并删除该终端显示屏？",
                  cancelText: "取消",
                  confirmText: "确定",
                  confirmBgColor: ThemeRepository.getInstance()
                      .getMinorRedColor_F95355());
              if (result ?? false) {
                if(widget?.terminalCount != null){
                  _viewModel?.unBindTerminal(context, widget?.hsn,
                      terminalCount: widget?.terminalCount, router: widget?.router);
                }else{
                  _viewModel?.unBindTerminal(context, widget?.hsn, router: widget?.router);
                }
              }
            },
            child: Container(
              padding: EdgeInsets.all(40),
              child: Text(
                "删除设备",
                style: TextStyle(
                    color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
                    fontSize: 14
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // void _toSetAutoOnOffTime()async{
  //
  //   BindingTerminalAutoOffStatusType autoOffStatusType;
  //   Map<String, dynamic> resultMap =
  //   await BindingTerminalAutoSwitchDialog.navigatorPushDialog(
  //       context,
  //       widget?.terminalInfoBean?.startDateTime,
  //       widget?.terminalInfoBean?.endDateTime,
  //       BindingTerminalCameraStatusTypeExtension.getStrToType(widget?.terminalInfoBean?.closeCamera) ==
  //           BindingTerminalCameraStatusType.open);
  //   if (resultMap == null || resultMap.isEmpty) {
  //     return;
  //   }
  //   widget?.terminalInfoBean?.startDateTime =
  //   resultMap[BINDING_TERMINAL_POP_START_DATE_TIME_KEY];
  //   widget?.terminalInfoBean?.endDateTime =
  //   resultMap[BINDING_TERMINAL_POP_END_DATE_TIME_KEY];
  //
  //   String autoOnOffTime = widget?.terminalInfoBean?.getAutoOffTimeStr();
  //   //auto_onoff 00未设置 01已设置
  //   if(StringUtils.isEmpty(autoOnOffTime)){
  //     //自动开关机时间为空，代表未设置
  //     _viewModel.setAutoOnOffTime(widget?.terminalInfoBean?.id,
  //         widget?.hsn, "01", widget?.terminalInfoBean?.autoOnoffTime, "00", "1,2,3,4,5", needPop: true);
  //   }else{
  //     _viewModel.setAutoOnOffTime(widget?.terminalInfoBean?.id,
  //         widget?.hsn, "01", autoOnOffTime, "01", "1,2,3,4,5", needPop: true);
  //   }
  //   setState(() {});
  // }

  Widget _toSplitLineWidget() {
    return Container(
      height: 0.5,
      margin: const EdgeInsets.only(left: 0, right: 0),
      color: ThemeRepository.getInstance().getLineColor_3A3F50(),
    );
  }

  double _getDistance(double value){
    if(0.0 == value){
      return 1.0;
    }
    if(1.0 == value){
      return 1.5;
    }
    if(2.0 == value){
      return 2.0;
    }
    if(3.0 == value){
      return 2.5;
    }
    if(4.0 == value){
      return 3.0;
    }
    return 2.0;
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      title: "更多设置",
      isShowBack: true,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  String getWeekAutoOnOffTimeStr(){
    if(_autoBean == null){
      return "";
    }
    if("01" == (_autoBean?.autoMon??"") && StringUtils.isNotEmpty(_autoBean?.monTime)){
      return "已启用";
    }
    if("01" == (_autoBean?.autoTues??"") && StringUtils.isNotEmpty(_autoBean?.tuesTime)){
      return "已启用";
    }
    if("01" == (_autoBean?.autoWed??"") && StringUtils.isNotEmpty(_autoBean?.wedTime)){
      return "已启用";
    }
    if("01" == (_autoBean?.autoThur??"") && StringUtils.isNotEmpty(_autoBean?.thurTime)){
      return "已启用";
    }
    if("01" == (_autoBean?.autoFri??"") && StringUtils.isNotEmpty(_autoBean?.friTime)){
      return "已启用";
    }
    if("01" == (_autoBean?.autoSat??"") && StringUtils.isNotEmpty(_autoBean?.satTime)){
      return "已启用";
    }
    if("01" == (_autoBean?.autoSun??"") && StringUtils.isNotEmpty(_autoBean?.sunTime)){
      return "已启用";
    }
    return "";
  }
}
